package leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2021-11-28 10:19
 **/
public class LeetCode567 {

    //优化后的滑动窗口
    public boolean checkInclusion(String s1, String s2) {
        int lens1 = s1.length();
        int lens2 = s2.length();

        if (lens1 > lens2) {
            return false;
        }

        int[] counts2 = new int[26];
        int diff = 0;
        for (int i = 0; i < lens1; i++) {
            --counts2[s1.charAt(i) - 'a'];
            ++counts2[s2.charAt(i) - 'a'];
        }

        for (int i = 0; i < 26; i++) {
            if (counts2[i] != 0) {
                diff++;
            }
        }

        if (diff == 0) {
            return true;
        }

        for (int i = 0; i < lens2 - lens1; i++) {
            if (counts2[s2.charAt(i) - 'a'] == 1) {
                diff--;
            } else if (counts2[s2.charAt(i) - 'a'] == 0) {
                diff++;
            }
            --counts2[s2.charAt(i) - 'a'];
            if (counts2[s2.charAt(i + lens1) - 'a'] == -1) {
                diff--;
            } else if (counts2[s2.charAt(i + lens1) - 'a'] == 0) {
                diff++;
            }
            ++counts2[s2.charAt(i + lens1) - 'a'];
            if (diff == 0) {
                return true;
            }

        }

        return false;
    }

    //滑动窗口
    /*public boolean checkInclusion(String s1, String s2) {
        int lens1 = s1.length();
        int lens2 = s2.length();

        if (lens1 > lens2) {
            return false;
        }

        int[] counts1 = new int[26];
        int[] counts2 = new int[26];
        for (int i = 0; i < lens1; i++) {
            ++counts1[s1.charAt(i) - 'a'];
            ++counts2[s2.charAt(i) - 'a'];
        }

        if (Arrays.equals(counts1, counts2)) {
            return true;
        }

        for (int i = 0; i < lens2 - lens1; i++) {
            --counts2[s2.charAt(i) - 'a'];
            ++counts2[s2.charAt(i + lens1) - 'a'];
            if (Arrays.equals(counts1, counts2)) {
                return true;
            }
        }

        return false;
    }*/

}
